# -*- coding: utf-8 -*-
"""
对接GPU服务器代码，整理对应的反馈结果
"""
import copy
import requests, json, logging, time, os
from pprint import pprint
from copy import deepcopy as deepcopy
from datetime import datetime
from pprint import pprint
from openai import OpenAI
from settings import *
from settings import prompt_toolkit
from settings import MISSING
from settings import \
    label_feeling_labels_zh, \
    Qwen_URL, \
    Qwen_turbo_online_base_url, \
    Qwen_turbo_online_api_key, \
    MODEL_FLAG
    # label_clarify_vehicle_relevant_labels, \
    # label_forum_labels, \
    # label_purchase_labels, \
    # label_sentiment_labels
    # # label_quality_labels_zh,\
    # # label_quality_labels_en,\
    # # label_quality_labels_translate,\
    # # label_csp_labels_zh,\
    # # label_csp_labels_convert,\
    # # label_feeling_labels_convert, \


from utils.tool import RetryManager

# 请求服务器
class QWENet(object):
    """
    QWENet 模型
    """


    def __init__(self):
        # local developed model
        self.url = Qwen_URL
        self.headers = {
            'accept': 'application/json',
            'Content-Type': 'application/json',
        }

        # ali online commercial model
        self.client = OpenAI(
            # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
            api_key=Qwen_turbo_online_api_key,
            base_url=Qwen_turbo_online_base_url
        )



    def request_local_model(self, content, max_tokens=200):
        data = {
            "model": "",
            "messages": [
                {
                    "role": "user",
                    "content": content,
                }
            ],
            "do_sample": False,
            "temperature": 0.2,
            "n": 1,
            "max_tokens": max_tokens,
            "stop": ["\n"],
            "stream": False
        }
        res = requests.post(
            self.url, headers=self.headers,
            data=json.dumps(data)
        )
        try:
            res = res.json()['choices'][0]['message']['content']
            res = json.loads(res.replace("'", '"'))
        except:
            res = []
        return res


    def request_commercial_model(self, content, max_tokens=500):
        completion = self.client.chat.completions.create(
            # model="qwen-turbo-latest",
            model="qwen-plus",
            messages=[
                {'role': 'user', 'content': content}
            ],
            temperature=0.1,
            stream=False,
            response_format={"type": "json_object"},
        )
        res = completion.choices[0].message.content
        if isinstance(res, list):
            return res
        else:
            try:
                res = json.loads(res.replace("'", '"'))
            except:
                res = []
            if isinstance(res, list):
                ...
            elif isinstance(res, dict):
                res = list(res.values())
            return res

    def content_requests(self, content, max_tokens=None):
        if MODEL_FLAG=='online':
            res = self.request_commercial_model(
                content=content,
                max_tokens=max_tokens
            )
        else:
            res = self.request_local_model(
                content=content,
                max_tokens=max_tokens
            )

        logging.info("")
        logging.info('TIME : {}'.format(datetime.now()))
        logging.info(content)
        logging.info(res)
        logging.info("")
        return res


qwen = QWENet()

retry_manager = RetryManager(
    max_retries=qwen_max_retries,
    delay=qwen_delay
)


class Analyze(object):
    """
    根据需求将 settings 中的 Prompt内容组装送入GPU模型处理
    """

    def __init__(self):
        self.label_feeling_labels_zh = label_feeling_labels_zh
        self.label_feeling_labels_zh_keys = copy.deepcopy(
            list(self.label_feeling_labels_zh.keys())
        )

    def label_feeling_labels_zh_values(self, key) -> list:
        if key in self.label_feeling_labels_zh_keys:
            return self.label_feeling_labels_zh[key]
        else:
            return []

    def clarify_vehicle_relevant(self, customer_voice):
        '''判断客户反馈是否和车辆相关，避免客户评价的是别的物品'''
        '''
        [
            "客户反馈和车辆相关",
            "客户反馈和车辆不相关",
            "客户反馈中无法判断是否和车辆相关"
        ]
        '''
        label_clarify_vehicle_relevant_labels = [
            "客户反馈和车辆相关",
            "客户反馈和车辆不相关",
            "客户反馈中无法判断是否和车辆相关"
        ]
        response_set = set()
        prompt = prompt_toolkit.clarify_vehicle_relevant_prompt(
            customer_voice=customer_voice
            # labels=label_clarify_vehicle_relevant_labels
        )
        res = qwen.content_requests(prompt, max_tokens=200)
        for r in res:
            if r not in label_clarify_vehicle_relevant_labels:
                ...
                # raise RuntimeError(f"ERROR clarify prompt {r} is not in clarify_labels")
            else:
                response_set.add(r)
        response_list = list(response_set)
        if len(response_list)==1:
            return response_list
        else:
            return ["客户反馈中无法判断是否和车辆相关"]


    def clarify_forum_labels(self, customer_voice):
        '''
        车辆质量与可靠性
        车辆评价体验
        车辆营销内容
        不同车型间对比
        车企商业信息
        社区与活动
        其他未分类信息
        '''
        label_forum_labels = [
            '车辆质量与可靠性',
            '车辆评价体验',
            '车辆营销内容',
            '不同车型间对比',
            '车企商业信息',
            '社区与活动',
            '其他未分类信息'
        ]
        response_set = set()
        # if MISSING not in label_forum_labels: # 20250415 : 直接将分类写入了prompt
        #     label_forum_labels.append(MISSING)
        prompt = prompt_toolkit.clarify_forum_labels(
            customer_voice=customer_voice
            # labels=label_forum_labels
        )
        res = qwen.content_requests(prompt, max_tokens=200)
        # if MISSING in res:
        #     res.remove(MISSING)
        for r in res:
            if r not in label_forum_labels:
                ...
                # raise RuntimeError(f"ERROR clarify quality {r} is not in clarify_quality")
            else:
                response_set.add(r)
        return list(response_set)


    def relevant2vehicle_prompt(self, customer_voice, vehicle):
        '''判断当前语句中，哪些语句与目标车型相关'''
        response_list = list()
        prompt = prompt_toolkit.relevant_sentence_prompt(
            customer_voice=customer_voice,
            vehicle=vehicle
        )
        res = qwen.content_requests(prompt, max_tokens=200)
        for r in res:
            if r not in response_list:
                response_list.append(r)

        if len(response_list):
            return ' '.join(response_list)
        else:
            return ''

    def purchase_prompt(self, customer_voice):
        '''判断客户购车欲望'''
        '''
        [
            '强烈购买车辆意愿或已购车',
            '中等购买车辆意愿',
            '低购买车辆意愿',
            '无法判别购车意愿'
        ]
        '''
        label_purchase_labels = [
            '强烈购买车辆意愿或已购车',
            '中等购买车辆意愿',
            '低购买车辆意愿',
            '无法判别购车意愿'
        ]
        response_set = set()
        prompt = prompt_toolkit.purchase_prompt(
            customer_voice=customer_voice
        )
        res = qwen.content_requests(prompt, max_tokens=100)
        for r in res:
            if r not in label_purchase_labels:
                ...
                # raise RuntimeError(f"ERROR purchase prompt {r} is not in purchase_labels")
            else:
                response_set.add(r)
        response_list = list(response_set)
        if len(response_list)==1:
            return response_list
        else:
            return ["无法判别购车意愿"]

    def first_sm_label(self, customer_voice):
        ''' Sales Marketing 一级标签 '''
        '''
        [
            '智能驾驶',
            '车辆部件',
            '车辆人车交互功能'
            ... ...
        ]
        '''
        sm_label_keys = self.label_feeling_labels_zh_keys
        response_set = set()
        prompt = prompt_toolkit.sm_label_1_prompt(
            customer_voice=customer_voice
        )
        res = qwen.content_requests(prompt, max_tokens=200)
        for r in res:
            if r not in sm_label_keys:
                ...
                # raise RuntimeError(f"ERROR first_csp_label {r} is not in labels")
            else:
                response_set.add(r)
        response_list = list(response_set)
        return response_list

    def second_sm_label(self,
                        customer_voice,
                        first_label):
        '''sales marketing 二级标签'''
        '''
        first_label = '智能驾驶'
        labels = [
            '盲区监测',
            '变道辅助',
            '车道偏离预警',
            ... ...
        ]
        '''
        sm_label_values = self.label_feeling_labels_zh_values(
            key=first_label
        )
        response_set = set()
        prompt = prompt_toolkit.sm_label_2_prompt(
            customer_voice=customer_voice,
            labels=sm_label_values
        )
        res = qwen.content_requests(prompt, max_tokens=200)
        for r in res:
            if r not in sm_label_values:
                ...
            else:
                response_set.add(r)
        response_list = list(response_set)
        return response_list


    def analyze(self,
                customer_voice,
                type,
                content=None,
                vehicle=''):
        if type == 'clean_sentence':
            return customer_voice

        elif type == 'clarify_vehicle_relevant':
            # 判断该句话是否和车辆相关
            clarify_prompt = retry_manager.execute(
                func=self.clarify_vehicle_relevant,
                customer_voice=customer_voice
            )
            return clarify_prompt

        elif type == 'clarify_forum':
            # 判别该句话属于哪种类型的内容
            clarify_forum = retry_manager.execute(
                func=self.clarify_forum_labels,
                customer_voice=customer_voice
            )
            return clarify_forum

        elif type=='sentence_split':
            relevant2vehicle = retry_manager.execute(
                func=self.relevant2vehicle_prompt,
                customer_voice=customer_voice,
                vehicle=vehicle
            )
            return relevant2vehicle

        elif type == 'purchase_prompt':
            # 判别该句话反应的用户购买欲望强度
            purchase_prompt = retry_manager.execute(
                func=self.purchase_prompt,
                customer_voice=customer_voice
            )
            return purchase_prompt

        elif type == 'sentiment':
            res_sentiment = retry_manager.execute(
                func=self.sentiment_prompt,
                customer_voice=customer_voice,
                content=content,
                vehicle=vehicle
            )
            return res_sentiment


        elif type == 'ner':
            ner_res = set()
            ner = retry_manager.execute(
                func=self.ner_prompt,
                customer_voice=customer_voice,
                content=content
            )
            for _ in ner:
                if _ not in customer_voice or len(_) == 0:
                    continue
                else:
                    ner_res.add(_)
            return list(ner_res)

        # TODO : 添加对应的 feelings 相关的标签
        elif type=='feel':
            res_feeling_labels_dict = {}

            res_label_1_list = self.first_sm_label(customer_voice)

            if len(res_label_1_list) == 0:
                return []

            for r in res_label_1_list:
                res_feeling_labels_dict.update({r: []})

            # 获取 feeling 二级标签
            for label_1 in res_feeling_labels_dict.keys():
                label_2_list = self.second_sm_label(
                    customer_voice=customer_voice,
                    first_label=label_1
                )
                for label_2 in label_2_list :
                    res_feeling_labels_dict[label_1].append(label_2)

            # 将 res_feeling_labels_dict 字典转换为列表的格式
            res_feeling_labels_list = []
            for KEY, VALUE in res_feeling_labels_dict.items():
                if len(VALUE):
                    for value in VALUE:
                        res_feeling_labels_list.append({
                            'feel_1' : KEY,
                            'feel_2': value
                        })
                else:
                    ...
            return res_feeling_labels_list



    def ner_prompt(self,
                   customer_voice,
                   content):
        '''根据客户反馈和对应的内容，找到客户语句中与之相关的文本'''
        prompt = prompt_toolkit.ner_prompt(
            customer_voice=customer_voice,
            content=content
        )
        res = qwen.content_requests(
            prompt,
            max_tokens=5000
        )
        # 然后去重一下
        res_set = set()
        for r in res :
            if r in customer_voice:
                res_set.add(r)
        res_list = list(res_set)
        return res_list

    def sentiment_prompt(self,
                         customer_voice,
                         content,
                         vehicle):
        '''根据客户反馈和对应的标签，实现对特定内容的情感倾向性评价'''
        '''
        [
            '正向情感-5', 
            '正向情感-4', 
            '中性情感-3', 
            '负向情感-2', 
            '负向情感-1'
        ]
        '''
        sentiment_labels = [
            '正向情感-5',
            '正向情感-4',
            '中性情感-3',
            '负向情感-2',
            '负向情感-1'
        ]
        if vehicle in customer_voice :
            ...
        else:
            vehicle = ''
        prompt = prompt_toolkit.sentiment_prompt(
            customer_voice=customer_voice,
            content=content,
            vehicle=vehicle
        )
        res = qwen.content_requests(prompt, max_tokens=20)

        if len(res) == 0:
            res = []
            return res
        elif len(res) > 1:
            res = ['中性情感-3']
        else:
            ...

        if res[0] in sentiment_labels:
            return res
        else:
            return ['中性情感-3']


class Assembly(object):
    """
    Assemble the result from Analyze
    """

    def __init__(self):
        self.analyze = Analyze()
        self.qwen_max_length = qwen_max_length

    def clean_sentence(self, customer_voice):
        customer_voice = customer_voice. \
            replace('\r', ''). \
            replace('\n', ''). \
            replace('\t', ''). \
            replace('"', ''). \
            replace("'", ""). \
            replace(' ', ""). \
            replace('“', ' '). \
            replace('”', ' '). \
            replace('{', ' '). \
            replace('}', ' ')
        if len(customer_voice) > self.qwen_max_length:
            customer_voice = customer_voice[: self.qwen_max_length]
        return customer_voice

    def sentiment(self, customer_voice, content, vehicle):
        return self.analyze.analyze(
            customer_voice=customer_voice,
            type='sentiment',
            content=content,
            vehicle=vehicle
        )

    def ner(self, customer_voice, content):
        return self.analyze.analyze(
            customer_voice=customer_voice,
            type='ner',
            content=content
        )

    def assemble(self,
                 sentence,
                 type='clean_sentence',
                 vehicle=''):
        customer_voice = self.clean_sentence(sentence)

        if type == 'clean_sentence':
            return customer_voice

        elif type == 'clarify_vehicle_relevant':
            return self.analyze.analyze(
                customer_voice=customer_voice,
                type=type
            )

        elif type == 'clarify_forum':
            return self.analyze.analyze(
                customer_voice=customer_voice,
                type=type
            )

        elif type=='sentence_split':
            return self.analyze.analyze(
                customer_voice=customer_voice,
                vehicle=vehicle,
                type=type
            )

        elif type == 'purchase_prompt':
            return self.analyze.analyze(
                customer_voice=customer_voice,
                type=type,
                vehicle=vehicle
            )


        elif type == 'feel':
            feeling_labels_list = self.analyze.analyze(
                customer_voice=customer_voice,
                type=type
            )
            response_feeling_zh_list = []
            for index in range(len(feeling_labels_list)):
                feel_1 = feeling_labels_list[index]['feel_1']
                feel_2 = feeling_labels_list[index]['feel_2']

                content_list = self.ner(
                    customer_voice = customer_voice,
                    content=str(feel_2)
                )
                if len(content_list):
                    content_list_zh_temp = ''.join(content_list)
                    sentiment = self.sentiment(
                        customer_voice = content_list_zh_temp,
                        content= str(feel_2),
                        vehicle=''
                    )
                else:
                    sentiment = []

                if len(content_list) and len(sentiment):
                    response_feeling_zh_list.append(
                        {
                            'feel_1' : feel_1,
                            'feel_2' : feel_2,
                            'content_list' : content_list,
                            'sentiment' : sentiment
                        }
                    )

                else:
                    ...
            return response_feeling_zh_list

        elif type == 'feel_withvehicle':
            feeling_labels_list = self.analyze.analyze(
                customer_voice=customer_voice,
                type='feel'
            )
            response_feeling_zh_list = []
            for index in range(len(feeling_labels_list)):
                feel_1 = feeling_labels_list[index]['feel_1']
                feel_2 = feeling_labels_list[index]['feel_2']

                content_list = self.ner(
                    customer_voice = customer_voice,
                    content=str(feel_2)
                )
                if len(content_list):
                    content_list_zh_temp = ''.join(content_list)
                    sentiment = self.sentiment(
                        customer_voice = content_list_zh_temp,
                        content= str(feel_2),
                        vehicle=vehicle
                    )
                else:
                    sentiment = []

                if len(content_list) and len(sentiment):
                    response_feeling_zh_list.append(
                        {
                            'feel_1' : feel_1,
                            'feel_2' : feel_2,
                            'content_list' : content_list,
                            'sentiment' : sentiment
                        }
                    )
                else:
                    ...
            return response_feeling_zh_list



if __name__ == "__main__":
    from pprint import pprint

    assemble = Assembly()
    sentence = """
优点:空间大、操控好、音响效果不错、续航真实！
缺点:没有座椅通风，安全带勒脖子！
"""
    print(len(sentence))
    start_time = time.time()
    a = assemble.assemble(
        sentence=sentence,
        type='quality'
    )
    end_time = time.time()
    print(sentence)
    pprint(a)
    print(end_time - start_time)







"""
def first_quality_label(self, customer_voice, labels):
    response_set = set()
    if MISSING not in labels:
        labels.append(MISSING)
    prompt = prompt_toolkit.quality_1_prompt(
        customer_voice=customer_voice,
        labels=labels
    )
    res = qwen.content_requests(prompt, max_tokens=200)
    if MISSING in res:
        res.remove(MISSING)
    for r in res:
        if r not in labels:
            ...
        #     raise RuntimeError(f"ERROR quality first label {r} is not in labels")
        else:
            response_set.add(r)
    return list(response_set)

def second_quality_label(self, customer_voice, first_label, labels):

    response_set = set()
    if MISSING not in labels:
        labels.append(MISSING)
    prompt = prompt_toolkit.quality_2_prompt(
        customer_voice=customer_voice,
        first_label=first_label,
        labels=labels
    )
    res = qwen.content_requests(prompt, max_tokens=200)
    if MISSING in res:
        res.remove(MISSING)
    for r in res:
        if r not in labels:
            ...
            # raise RuntimeError(f"ERROR quality second label {r} is not in labels")
        else:
            response_set.add(r)
    return list(response_set)

"""


"""

#
# class Translator:
#     def __init__(self):
#         self.url = "http://{host}:{port}/translate".format(
#             host=translator_host,
#             port=translator_port
#         )
#
#         # 整理 Quality labels translation dict
#         self.quality_label_zh2en = {}
#         for zh, en in label_quality_labels_translate.items():
#             function_group_zh, problem_zh = zh.split('@@')
#             function_group_en, problem_en = en.split('@@')
#             self.quality_label_zh2en.update({
#                 function_group_zh: function_group_en,
#                 problem_zh: problem_en
#             })
#
#         # 整理 CSP labels translation dict
#         self.csp_label_zh2en = label_csp_labels_convert
#
#         # 整理 feeling labels translation dict
#         self.feeling_label_zh2en = label_feeling_labels_convert
#
#     def translate_quality_labels(self, quality_zh_label):
#         if quality_zh_label in self.quality_label_zh2en.keys():
#             return self.quality_label_zh2en[quality_zh_label]
#         else:
#             return ''
#
#     def translate_csp_labels(self, csp_zh_label):
#         if csp_zh_label in self.csp_label_zh2en.keys():
#             return self.csp_label_zh2en[csp_zh_label]
#         else:
#             return ''
#
#     def translate_feeling_labels(self, feeling_zh_label):
#         if feeling_zh_label in self.feeling_label_zh2en.keys():
#             return self.feeling_label_zh2en[feeling_zh_label]
#         else:
#             return ''
#
#     def translate(self, sentence, password):
#         '''
#         use r'\n' symbol to split the sentence
#         the target customer voice has already remove r'\n'
#         '''
#         data = {
#             'sentence': sentence,
#             'password': password
#         }
#         res = requests.post(
#             url=self.url, data=data
#         )
#         try:
#             result = json.loads(res.content.decode('unicode_escape'))
#         except Exception as e:
#             logging.info(
#                 {
#                     'type': 'ERROR',
#                     'name': 'translator',
#                     'info': str(e),
#                     'date': str(datetime.now())
#                 }
#             )
#             result = {}
#         return result

"""

"""
        elif type == 'quality':
            # 创建一个循环类型的函数，然后循环最终得到结果
            res_quality_labels_dict = {}

            def get_qwen_quality(customer_voice, label):
                res_labels = retry_manager.execute(
                    func=self.first_quality_label,
                    customer_voice=customer_voice,
                    labels=label
                )
                return res_labels

            def get_qwen_quality_2(customer_voice,
                                   first_quality_label,
                                   second_quality_label_list):
                res_labels = retry_manager.execute(
                    func=self.second_quality_label,
                    customer_voice=customer_voice,
                    first_label=first_quality_label,
                    labels=second_quality_label_list
                )
                return res_labels

            # 获取 Quality 一级标签
            quality_first_labels = copy.deepcopy(
                list(label_quality_labels_zh.keys())
            )
            res_label_1_list = get_qwen_quality(customer_voice, quality_first_labels)
            if len(res_label_1_list) == 0:
                return []  # 如果没有一级标签列表直接return []
            for r in res_label_1_list:
                res_quality_labels_dict.update({r: []})

            # 获取 Quality 二级标签
            for label_1 in res_quality_labels_dict.keys():
                quality_second_labels = list(
                    copy.deepcopy(
                        list(label_quality_labels_zh[label_1])
                    )
                )
                res_label_2_list = get_qwen_quality_2(
                    customer_voice=customer_voice,
                    first_quality_label=label_1,
                    second_quality_label_list=quality_second_labels
                )
                for r in res_label_2_list:
                    res_quality_labels_dict[label_1].append(r)

            # 质量这部分直接把不能完全识别质量问题的标签删除掉
            res_quality_labels_list = []
            for function_group, problems in res_quality_labels_dict.items():
                if len(problems) == 0:
                    ...
                else:
                    for problem in problems:
                        res_quality_labels_list.append({
                            'function_group': function_group,
                            'problem': problem
                        })
            return res_quality_labels_list
"""




"""
   
        # elif type == 'csp':
        #     # 创建一个循环类型的函数，然后循环最终得到结果
        #     res_csp_labels_dict = {}
        #     # 这里应该是一个列表，然后记录每一个对应的 ··CSP LABEL··
        # 
        #     def get_qwen_csp_1(customer_voice, label):
        #         res_labels = retry_manager.execute(
        #             func=self.first_sm_label,
        #             customer_voice=customer_voice,
        #             labels=label,
        #             vehicle=vehicle
        #         )
        #         return res_labels
        # 
        #     def get_qwen_csp_2(customer_voice,
        #                        first_csp_label,
        #                        second_csp_label_list):
        #         res_labels = retry_manager.execute(
        #             func=self.second_sm_label,
        #             customer_voice=customer_voice,
        #             first_label=first_csp_label,
        #             labels=second_csp_label_list,
        #             vehicle=vehicle
        #         )
        #         return res_labels
        # 
        #     # 获取 CSP 一级标签
        #     csp_first_labels = copy.deepcopy(
        #         list(label_csp_labels_zh.keys())
        #     )
        #     csp_first_labels = [_ for _ in csp_first_labels if len(_)]
        #     res_label_1_list = get_qwen_csp_1(
        #         customer_voice=customer_voice,
        #         label=csp_first_labels
        #     )
        #     if len(res_label_1_list) == 0:
        #         return []  # 如果没有一级标签列表直接 return []
        #     for r in res_label_1_list:
        #         res_csp_labels_dict.update({r: []})
        # 
        #     # 获取 CSP 二级标签
        #     for label_1 in res_csp_labels_dict.keys():
        #         if len(label_csp_labels_zh[label_1]) > 0:
        #             csp_second_labels = list(
        #                 copy.deepcopy(
        #                     label_csp_labels_zh[label_1]
        #                 )
        #             )
        #             csp_second_labels = [_ for _ in csp_second_labels if len(_)]
        #             if len(csp_second_labels):
        #                 res_label_2_list = get_qwen_csp_2(
        #                     customer_voice=customer_voice,
        #                     first_csp_label=label_1,
        #                     second_csp_label_list=csp_second_labels
        #                 )
        #                 for r in res_label_2_list:
        #                     res_csp_labels_dict[label_1].append(r)
        #         else:
        #             ...

            # # 获取 CSP 三级标签
            # for label_1, value_1 in res_csp_labels_dict.items():
            #     for label_2, value_2 in value_1.items():
            #         csp_third_labels = list(
            #             copy.deepcopy(
            #                 list(label_csp_labels_zh[label_1][label_2])
            #             )
            #         )
            #         csp_third_labels = [_ for _ in csp_third_labels if len(_)]
            #         if len(csp_third_labels) > 0:
            #             res_label_3_list = get_qwen_csp_3(
            #                 customer_voice=customer_voice,
            #                 first_csp_label=label_2,
            #                 second_csp_label_list=csp_third_labels
            #             )
            #             for r in res_label_3_list:
            #                 res_csp_labels_dict[label_1][label_2].append(r)
            #         else:
            #             ...
            # # 获取 CSP 四级标签
            # for label_1, value_1 in res_csp_labels_dict.items():
            #     for label_2, value_2 in value_1.items():
            #         for label_3, value_3 in value_2.items():
            #             csp_fourth_labels = list(
            #                 copy.deepcopy(
            #                     list(label_csp_labels_zh[label_1][label_2][label_3])
            #                 )
            #             )
            #             csp_fourth_labels = [_ for _ in csp_fourth_labels if len(_)]
            #             if len(csp_fourth_labels) > 0 :
            #                 if len(csp_fourth_labels):
            #                     res_label_3_list = get_qwen_csp_4(
            #                         customer_voice=customer_voice,
            #                         first_csp_label=label_3,
            #                         second_csp_label_list=csp_fourth_labels
            #                     )
            #                     for r in res_label_3_list:
            #                         res_csp_labels_dict[label_1][label_2][label_3].append(r)
            #             else:
            #                 ...

            {'驾舱内部件': {'音响': ['音效模式']}, 
            '三电系统': {'电驱电机': [], '电池管理系统 BMS': []}, 
            '其它安全': {}, 
            '车身部件及空调': {'座椅': ['座椅通风'], 
            '空调': ['温度调节']}, 
            '底盘部件': {'转向': []}}
            [{'csp_1': '其它安全', 'csp_2': '', 'csp_3': ''}, 
            {'csp_1': '三电系统', 'csp_2': '电池管理系统 BMS', 'csp_3': ''}, 
            {'csp_1': '三电系统', 'csp_2': '电驱电机', 'csp_3': ''}, 
            {'csp_1': '车身部件及空调', 'csp_2': '座椅', 'csp_3': '座椅通风'}, 
            {'csp_1': '车身部件及空调', 'csp_2': '空调', 'csp_3': '温度调节'},
            {'csp_1': '底盘部件', 'csp_2': '转向', 'csp_3': ''}, 
            {'csp_1': '驾舱内部件', 'csp_2': '音响', 'csp_3': '音效模式'}]
            # 为了保持系统和之前一样，对于CSP这里依旧赋值 csp_3 = '' 空字符串，为了保证后端不用动
            def convert_to_list(res_csp_labels_dict,
                                res_csp_labels_list):
                for csp_1, value_1 in res_csp_labels_dict.items():
                    if len(value_1):
                        for csp_2 in value_1:
                            res_csp_labels_list.append({'csp_1': csp_1, 'csp_2': csp_2, 'csp_3': ''})
                    else:
                        res_csp_labels_list.append({'csp_1' : csp_1, 'csp_2' : '', 'csp_3' : ''})

                return res_csp_labels_list

            # 最后将 res_csp_labels_dict 转换为 res_csp_labels_list
            res_csp_labels_list = []
            if len(res_csp_labels_dict.keys()):
                res_csp_labels_list = convert_to_list(
                    res_csp_labels_dict,
                    res_csp_labels_list
                )
            else:
                ...
            return res_csp_labels_list

"""

"""
        elif type == 'quality':
            # 识别客户反馈中的质量相关问题，单纯识别质量问题和情感倾向，不用NER
            # 对于质量投诉网站的数据，还是继续使用原来BERT训练的数据
            # 这个模块，绝大部分情况下不使用，只在演示的时候略微用一下
            quality_zh_list = self.analyze.analyze(
                customer_voice=customer_voice,
                type=type
            )
            quality_en_list = []
            for quality_zh in quality_zh_list:
                function_group_zh = quality_zh['function_group']
                problem_zh = quality_zh['problem']
                quality_en_list.append(
                    {
                        'function_group': self.translator.translate_quality_labels(function_group_zh),
                        'problem': self.translator.translate_quality_labels(problem_zh),
                    }
                )
            return [quality_zh_list, quality_en_list]


        elif type == 'quality_and_ner':
            # 识别客户抱怨的质量问题，并且识别其中的NER相关的内容
            # zh
            quality_zh_list = self.analyze.analyze(
                customer_voice=customer_voice,
                type='quality'
            )

            # 组装 zh , en
            response_quality_zh = []
            response_quality_en = []

            for index in range(len(quality_zh_list)):
                function_group_zh = quality_zh_list[index]['function_group']
                problem_zh = quality_zh_list[index]['problem']
                content_list_zh = self.ner(customer_voice=customer_voice,
                                           content=str(function_group_zh) + str(problem_zh))
                sentiment_zh, sentiment_en = self.sentiment(customer_voice=customer_voice,
                                                            content=str(function_group_zh) + str(problem_zh))
                if '负向' in sentiment_zh:
                    response_quality_zh.append(
                        {
                            'function_group': function_group_zh,
                            'problem': problem_zh,
                            'content_list': content_list_zh,
                            'sentiment': '负向情感'
                        }
                    )
                    content_list_en = content_list_zh
                    response_quality_en.append(
                        {
                            'function_group': self.translator.translate_quality_labels(function_group_zh),
                            'problem': self.translator.translate_quality_labels(problem_zh),
                            'content_list': content_list_en,
                            'sentiment': 'negative'
                        }
                    )
            return [response_quality_zh, response_quality_en]

"""


"""

        elif type == 'csp':
            csp_zh_list = self.analyze.analyze(
                customer_voice=customer_voice,
                type=type,
                vehicle=vehicle
            )
            # [{'csp_1': '其它安全', 'csp_2': '', 'csp_3': ''}, {'csp_1': '三电系统', 'csp_2': '电池管理系统 BMS', 'csp_3': ''}, {'csp_1': '三电系统', 'csp_2': '电驱电机', 'csp_3': ''}, {'csp_1': '车身部件及空调', 'csp_2': '座椅', 'csp_3': '座椅通风'}, {'csp_1': '车身部件及空调', 'csp_2': '空调', 'csp_3': '温度调节'}, {'csp_1': '底盘部件', 'csp_2': '转向', 'csp_3': ''}, {'csp_1': '驾舱内部件', 'csp_2': '音响', 'csp_3': '音效模式'}]
            response_csp_zh_list = []
            response_csp_en_list = []

            for index in range(len(csp_zh_list)):
                csp_1 = csp_zh_list[index]['csp_1']
                csp_2 = csp_zh_list[index]['csp_2']
                # csp_3 = csp_zh_list[index]['csp_3']
                csp_3 = ''
                # 首先找 content_list / sentiment_zh，对csp_1 , csp_2 等有数据的放入最后一组数据，效果更好

                if len(csp_2) > 0:
                    content_csp = csp_1 + "-" + csp_2
                else:
                    content_csp = csp_1

                content_list_zh = self.ner(customer_voice=customer_voice,
                                           content=content_csp)
                content_list_en = content_list_zh

                content_list_zh_temp = '||'.join(content_list_zh)
                sentiment_zh, sentiment_en = self.sentiment(
                    customer_voice=content_list_zh_temp,
                    content=content_csp
                )

                if len(content_list_zh) and len(sentiment_zh):
                    response_csp_zh_list.append(
                        {
                            'csp_1': csp_1,
                            'csp_2': csp_2,
                            'csp_3': csp_3,
                            'content_list': content_list_zh,
                            'sentiment': sentiment_zh
                        }
                    )
                    response_csp_en_list.append(
                        {
                            'csp_1': self.translator.translate_csp_labels(csp_1),
                            'csp_2': self.translator.translate_csp_labels(csp_2),
                            'csp_3': self.translator.translate_csp_labels(csp_3),
                            'content_list': content_list_en,
                            'sentiment': sentiment_en
                        }
                    )
                else:
                    # response_csp_zh_list.append(
                    #     {
                    #         'csp_1': csp_1,
                    #         'csp_2': csp_2,
                    #         'csp_3': csp_3,
                    #         'content_list': content_list_zh,
                    #         'sentiment': sentiment_zh
                    #     }
                    # )
                    # response_csp_en_list.append(
                    #     {
                    #         'csp_1': self.translator.translate_csp_labels(csp_1),
                    #         'csp_2': self.translator.translate_csp_labels(csp_2),
                    #         'csp_3': self.translator.translate_csp_labels(csp_3),
                    #         'content_list': content_list_en,
                    #         'sentiment': sentiment_en
                    #     }
                    # )
                    # logging.info(
                    #     {
                    #         'type': 'ERROR',
                    #         'name': 'qwen2',
                    #         'info': 'csp-1082 , the content list error',
                    #         'date': str(datetime.now())
                    #     }
                    # )
                    ...
            return [response_csp_zh_list, response_csp_en_list]

"""

